<template>
  <a-spin :spinning="spinning">
    <a-form :form="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" labelAlign="left">
      <a-row :gutter="16" type="flex">
        <a-col :span="8" class="left">
          <a-card :bordered="false" style="height: 100%">
            <p class="card-title">基本信息</p>
            <a-form-item label="区/县">
              <a-select
                v-decorator="['RegionNo', { rules: [{ required: true, message: '请选择区/县' }] }]"
                placeholder="请选择区/县"
                disabled
              >
                <a-select-option :value="item.ID" v-for="item in districtOptions" :key="item.ID"
                  >{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="社区/乡镇">
              <a-select
                v-decorator="['TownshipNo', { rules: [{ required: true, message: '请选择社区/乡镇' }] }]"
                placeholder="请选择社区/乡镇"
                disabled
              >
                <a-select-option :value="item.ID" v-for="item in TownshipOptions" :key="item.ID"
                  >{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="申请家庭类别">
              <a-select
                v-decorator="[
                  'ApplyClass',
                  { initialValue: '自行备案', rules: [{ required: true, message: '请选择申请家庭类别' }] },
                ]"
                placeholder="请选择申请家庭类别"
              >
                <a-select-option value="自行备案">自行备案 </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="家庭（辈）">
              <a-input-number
                :min="0"
                :precision="0"
                placeholder="请输入家庭（辈）"
                v-decorator="['StrDegress', { rules: [{ required: true, message: '请输入家庭（辈）' }] }]"
              />
            </a-form-item>
            <a-form-item label="保障方式">
              <a-select
                v-decorator="['CityVfyAssign', { rules: [{ required: true, message: '请选择保障方式' }] }]"
                placeholder="请选择保障方式"
              >
                <a-select-option value="1">无保障</a-select-option>
                <a-select-option value="3">实物安置</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              label="申请家庭类型"
              v-show="['备案', '共有产权', '其他'].includes(form.getFieldValue('ApplyClass'))"
            >
              <a-select
                v-decorator="[
                  'ApplyClassCategory',
                  {
                    initialValue: '',
                    rules: [
                      {
                        required: ['备案', '共有产权', '其他'].includes(form.getFieldValue('ApplyClass')),
                        message: '请选择申请家庭类型',
                      },
                    ],
                  },
                ]"
                placeholder="请选择申请家庭类型"
              >
                <a-select-option :value="item.DROPVALUE" v-for="item in familyMoldOptions" :key="item.DROPVALUE"
                  >{{ item.DROPVALUE }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="备案类型" v-show="form.getFieldValue('ApplyClass') === '备案'">
              <a-select
                v-decorator="[
                  'ClassName',
                  {
                    initialValue: '',
                    rules: [{ required: form.getFieldValue('ApplyClass') === '备案', message: '请选择备案类型' }],
                  },
                ]"
                placeholder="请选择备案类型"
              >
                <a-select-option :value="item.DROPKEY" v-for="item in classNameOptions" :key="item.DROPKEY"
                  >{{ item.DROPVALUE }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="现住房性质">
              <a-select
                v-decorator="['HousCategory', { rules: [{ required: true, message: '请选择现住房性质' }] }]"
                placeholder="请选择现住房性质"
                @change="handleHousCategoryChange"
              >
                <a-select-option :value="item.DROPVALUE" v-for="item in housingNatureOptions" :key="item.DROPKEY"
                  >{{ item.DROPVALUE }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="房屋总建筑面积㎡" extra="仅计算自有产权房个人产权面积总和">
              <a-input-number
                :min="0"
                disabled
                v-decorator="['StrLiveHousingArea', { rules: [{ required: true, message: '请输入房屋总建筑面积' }] }]"
                :formatter="(value) => `${value}㎡`"
                :parser="(value) => value.replace('㎡', '')"
              />
            </a-form-item>
            <a-form-item
              label="核定人均收入"
              v-show="['备案', '共有产权', '其他'].includes(form.getFieldValue('ApplyClass'))"
            >
              <a-input-number
                :min="0"
                v-decorator="[
                  'CityVfyIncome',
                  {
                    initialValue: '',
                    rules: [
                      {
                        required: ['备案', '共有产权', '其他'].includes(form.getFieldValue('ApplyClass')),
                        message: '请输入核定人均收入',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
            <a-form-item label="核定保障人数" extra="仅计算保障成员人数">
              <a-input-number
                disabled
                :min="0"
                v-decorator="['CityVfyNumber', { rules: [{ required: true, message: '请输入核定保障人数' }] }]"
              />
            </a-form-item>
            <a-form-item label="核定人均面积㎡" extra="房屋总建筑面积÷核定保障人数">
              <a-input-number
                disabled
                :min="0"
                v-decorator="['CityVfyAreaPer', { rules: [{ required: true, message: '请输入核定人均面积' }] }]"
                :formatter="(value) => `${value}㎡`"
                :parser="(value) => value.replace('㎡', '')"
              />
            </a-form-item>
          </a-card>
        </a-col>
        <a-col :span="16" class="right">
          <a-card :bordered="false">
            <a-space direction="vertical" size="large" style="width: 100%">
              <div>
                <a-space align="baseline" size="large">
                  <p class="card-title">保障成员名单</p>
                  <y-button icon="user-add" type="success" @click="handleAdd('visibleAssure')">添加保障成员</y-button>
                </a-space>
                <s-table
                  ref="assureTable"
                  :rowKey="(record, index) => index"
                  size="middle"
                  :ableExport="false"
                  :columns="assureColumns"
                  :data="assureLoadData"
                >
                  <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
                  <a-tag slot="Sexs" slot-scope="sex">{{ sex }}</a-tag>
                  <div slot="action" slot-scope="text, record, index">
                    <y-button type="link" @click="handleEdit(record, index, 'visibleAssure')">编辑</y-button>
                    <a-popconfirm title="确认删除此保障成员?" @confirm="handleDel(record, index, 'assure')">
                      <span class="text-error m-l-10">删除</span>
                    </a-popconfirm>
                  </div>
                </s-table>
              </div>
              <div v-if="form.getFieldValue('HousCategory') === '承租公房'">
                <a-space align="baseline" size="large">
                  <p class="card-title">住房情况填写</p>
                  <y-button icon="home" type="success" @click="handleAdd('visibleCzgf')">添加承租公房情况</y-button>
                </a-space>
                <s-table
                  ref="czgfTable"
                  :rowKey="(record, index) => index"
                  size="middle"
                  :ableExport="false"
                  :columns="czgfColumns"
                  :data="czgfLoadData"
                >
                  <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
                  <div slot="action" slot-scope="text, record, index">
                    <y-button type="link" @click="handleEdit(record, index, 'visibleCzgf')">编辑</y-button>
                    <a-popconfirm title="确认删除此住房情况信息?" @confirm="handleDel(record, index, 'czgf')">
                      <span class="text-error m-l-10">删除</span>
                    </a-popconfirm>
                  </div>
                </s-table>
              </div>
              <div v-if="form.getFieldValue('HousCategory') === '自有产权房'">
                <a-space align="baseline" size="large">
                  <p class="card-title">住房情况填写</p>
                  <y-button icon="home" type="success" @click="handleAdd('visibleZycq')">添加自有产权房情况</y-button>
                  <p class="card-title" style="font-size: 16px">
                    (<span style="color: #f00">房屋总建筑面积㎡等于，自有产权房个人产权面积总和</span>)
                  </p>
                </a-space>
                <s-table
                  ref="zycqTable"
                  :rowKey="(record, index) => index"
                  size="middle"
                  :ableExport="false"
                  :columns="zycqColumns"
                  :data="zycqLoadData"
                >
                  <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
                  <div slot="action" slot-scope="text, record, index">
                    <y-button type="link" @click="handleEdit(record, index, 'visibleZycq')">编辑</y-button>
                    <a-popconfirm title="确认删除此住房情况信息?" @confirm="handleDel(record, index, 'zycq')">
                      <span class="text-error m-l-10">删除</span>
                    </a-popconfirm>
                  </div>
                </s-table>
              </div>
            </a-space>
          </a-card>
        </a-col>
      </a-row>
      <assureForm
        :visible.sync="visibleAssure"
        :data="visibleAssureData"
        :isapplicant="applicant"
        :ifLowObjects="form.getFieldValue('ApplyClass')"
        :hasAapplicant="hasAapplicant"
        @change="handleTableFormChange($event, 'assure')"
      />
      <unAssureForm
        :visible.sync="visibleUnAssure"
        :data="visibleUnAssureData"
        @change="handleTableFormChange($event, 'unAssure')"
      />
      <ownedPropertyForm
        :visible.sync="visibleZycq"
        :data="visibleZycqData"
        :options="assureOptions"
        @change="handleTableFormChange($event, 'zycq')"
      />
      <leaseHouseForm
        :visible.sync="visibleCzgf"
        :data="visibleCzgfData"
        :options="assureOptions"
        @change="handleTableFormChange($event, 'czgf')"
      />
    </a-form>
  </a-spin>
</template>

<script>
import assureForm from './components/assureForm'
import unAssureForm from './components/unAssureForm'
import ownedPropertyForm from './components/ownedPropertyForm'
import leaseHouseForm from './components/leaseHouseForm'
import { getDeptDropList } from '@/api/communityReviewManagement'
import { getDepartmentInfos } from '@/api/system'
import { getDropdownList } from '@/api/common'
import { mapGetters } from 'vuex'
import { STable } from '@/components'
import BigNumber from 'bignumber.js'
import pick from 'lodash.pick'
export default {
  props: {
    data: {
      type: Object,
      default: () => {},
    },
  },
  provide() {
    return {
      hasIDCard: (value) => {
        return this.assureData.some((e) => e.IDCards === value) || this.unAssureData.some((e) => e.FIDCard === value)
      },
      applicationPerson: () => {
        return this.assureData.find((e) => e.Relation === 0)
      },
    }
  },
  components: {
    assureForm,
    unAssureForm,
    ownedPropertyForm,
    leaseHouseForm,
    STable,
  },
  computed: {
    ...mapGetters(['userid', 'userInfo']),
    hasAapplicant() {
      const item = this.assureData.find((e) => e.Relation === 0)
      return !!item
    },
    assureOptions() {
      const arr = [[], []]
      arr[0] = this.assureData.map((e) => {
        return {
          name: e.Name,
          idCard: e.IDCards,
        }
      })
      arr[1] = this.unAssureData.map((e) => {
        return {
          name: e.FName,
          idCard: e.FIDCard,
        }
      })
      return arr
    },
  },
  watch: {
    zycqData: {
      deep: true,
      immediate: true,
      handler(n) {
        this.computedArea()
      },
    },
    assureData: {
      deep: true,
      immediate: true,
      handler(n) {
        this.computedArea()
      },
    },
  },
  data() {
    return {
      spinning: false,
      visibleAssure: false,
      applicant: true,
      visibleAssureData: {},
      visibleUnAssure: false,
      visibleUnAssureData: {},
      visibleZycq: false,
      visibleZycqData: {},
      visibleCzgf: false,
      visibleCzgfData: {},
      editIndex: '',
      form: this.$form.createForm(this, { name: 'info' }),
      subsidyForm: this.$form.createForm(this, { name: 'subsidy' }),
      oldSMoney: '0',
      districtOptions: [],
      TownshipOptions: [],
      familyTypeOptions: [],
      housingNatureOptions: [],
      classNameOptions: [],
      familyMoldOptions: [],
      // 保障成员
      assureColumns: [
        {
          title: '序号',
          key: 'index',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '姓名',
          key: 'Name',
          dataIndex: 'Name',
          align: 'center',
        },
        {
          title: '性别',
          key: 'Sexs',
          dataIndex: 'Sexs',
          align: 'center',
          scopedSlots: { customRender: 'Sexs' },
        },
        {
          title: '身份证号',
          key: 'IDCards',
          dataIndex: 'IDCards',
          align: 'center',
        },
        {
          title: '户籍信息',
          key: 'ApplyTypes',
          dataIndex: 'ApplyTypes',
          align: 'center',
        },
        {
          title: '与申请人关系',
          key: 'RelationName',
          dataIndex: 'RelationName',
          align: 'center',
        },
        {
          title: '操作',
          width: 140,
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      assureData: [],
      // 未纳入保障成员
      unAssureColumns: [
        {
          title: '序号',
          key: 'index',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '姓名',
          key: 'FName',
          dataIndex: 'FName',
          align: 'center',
        },
        {
          title: '身份证号',
          key: 'FIDCard',
          dataIndex: 'FIDCard',
          align: 'center',
        },
        {
          title: '户籍信息',
          key: 'Category',
          dataIndex: 'Category',
          align: 'center',
        },
        {
          title: '与申请人关系',
          key: 'FRelation',
          dataIndex: 'FRelation',
          align: 'center',
        },
        {
          title: '操作',
          width: 140,
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      unAssureData: [],
      // 承租公房
      czgfColumns: [
        {
          title: '序号',
          key: 'index',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '成员类别',
          key: 'DetailCategory',
          dataIndex: 'DetailCategory',
          align: 'center',
        },
        {
          title: '姓名',
          key: 'DetailName',
          dataIndex: 'DetailName',
          align: 'center',
        },
        {
          title: '公司所有权单位名称',
          key: 'PublicUnit',
          dataIndex: 'PublicUnit',
          align: 'center',
        },
        {
          title: '租住公房建筑面积(m²)',
          key: 'PublicArea',
          dataIndex: 'PublicArea',
          align: 'center',
        },
        {
          title: '操作',
          width: 140,
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      czgfData: [],
      IDLIST: '',
      // 自由产权房子
      zycqColumns: [
        {
          title: '序号',
          key: 'index',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '成员类别',
          key: 'DetailCategory',
          dataIndex: 'DetailCategory',
          align: 'center',
        },
        {
          title: '姓名',
          key: 'DetailName',
          dataIndex: 'DetailName',
          align: 'center',
        },
        {
          title: '自有产权房产权人姓名',
          key: 'PropertyName',
          dataIndex: 'PropertyName',
          align: 'center',
        },
        {
          title: '自有产权房建筑面积(m²)',
          key: 'PropertyArea',
          dataIndex: 'PropertyArea',
          align: 'center',
        },
        {
          title: '自有产权房个人产权面积(m²)',
          key: 'PropertyOwnArea',
          dataIndex: 'PropertyOwnArea',
          align: 'center',
        },
        {
          title: '操作',
          width: 140,
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      zycqData: [],
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    assureLoadData(parameter) {
      return this.tableLoadData(parameter, 'assure')
    },
    unAssureLoadData(parameter) {
      return this.tableLoadData(parameter, 'unAssure')
    },
    czgfLoadData(parameter) {
      return this.tableLoadData(parameter, 'czgf')
    },
    zycqLoadData(parameter) {
      return this.tableLoadData(parameter, 'zycq')
    },
    tableLoadData(parameter, key) {
      const data = this[`${key}Data`]
      return Promise.resolve({
        data,
        count: data.length,
      })
    },
    fetchData() {
      this.spinning = true
      const $getDeptDropList = getDeptDropList({ userid: this.userid })
      const getDepartmentInfo = getDepartmentInfos({ deptID: this.userInfo.DeptID })
      const getFamilyType = getDropdownList({ PmKey: 'FamilyType' })
      const getHousingNature = getDropdownList({ PmKey: 'housingNature' })
      const getClassName = getDropdownList({ PmKey: 'ClassName' })
      const getFamilyMold = getDropdownList({ PmKey: 'FamilyMold' })
      Promise.all([$getDeptDropList, getDepartmentInfo, getFamilyType, getHousingNature, getClassName, getFamilyMold])
        .then((res) => {
          this.districtOptions = res[0][0].children
          const PID = Number(res[1].data.PID)
          const Township = this.districtOptions.find((e) => e.ID === PID)
          if (Township) {
            this.TownshipOptions = Township.children
            this.form.setFieldsValue({
              RegionNo: PID,
              TownshipNo: Number(this.userInfo.DeptID),
            })
          }
          this.familyTypeOptions = res[2]
          this.housingNatureOptions = res[3]
          this.classNameOptions = res[4]
          this.familyMoldOptions = res[5]
          // 修改
          if (!this.$isEmpty(this.data)) {
            this.form.setFieldsValue(
              pick(this.data, [
                'RegionNo',
                'TownshipNo',
                'ApplyClass',
                'StrDegress',
                'CityVfyAssign',
                'HousCategory',
                'StrLiveHousingArea',
                'CityVfyIncome',
                'ApplyClassCategory',
                'CityVfyNumber',
                'CityVfyAreaPer',
              ])
            )
            if (this.data.ClassName) {
              this.form.setFieldsValue({
                ClassName: Number(this.data.ClassName),
              })
            }
            this.TownshipOptions = this.districtOptions.find((e) => e.ID === this.data.RegionNo).children
            this.assureData = this.data.proposerdetail.map((e) => {
              const numberKey = ['Nations', 'Relation', 'College', 'Profession', 'DisabilityTypes', 'DisabilityLevels']
              numberKey.forEach((key) => {
                if (e[key]) {
                  e[key] = Number(e[key])
                }
              })
              return e
            })
            this.unAssureData = this.data.proposerfdetail
            this.$refs.assureTable.refresh(true)
            if (this.data.HousCategory === '自有产权房') {
              this.zycqData = this.data.proposerdetailhouses
              this.$nextTick(() => {
                this.$refs.zycqTable.refresh(true)
              })
            }
            if (this.data.HousCategory === '承租公房') {
              this.czgfData = this.data.proposerdetailhouses
              this.$nextTick(() => {
                this.$refs.czgfTable.refresh(true)
              })
            }
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    handleSubmit() {
      return new Promise((resolve, reject) => {
        this.form.validateFields((err, values) => {
          const zeros = this.assureData.filter((item) => item.Relation === 0)
          if (zeros.length >= 2) {
            this.$message.error('只能有一个申请人')
            return
          }
          if (zeros.length == 0) {
            this.$message.error('必须要有一个申请人')
            return
          }
          if (!err) {
            if (this.$isEmpty(this.assureData)) {
              this.$message.error('请添加保障成员')
              return
            }
            if (values.HousCategory === '自有产权房' && this.$isEmpty(this.zycqData)) {
              this.$message.error('请填写自有产权房情况')
              return
            }
            if (values.HousCategory === '承租公房' && this.$isEmpty(this.czgfData)) {
              this.$message.error('请填写承租公房情况')
              return
            }
            const subsidyData = this.subsidyForm.getFieldsValue()
            const data = Object.assign({}, values, {
              proposerdetail: this.assureData,
              proposerfdetail: this.unAssureData,
              IDLIST: this.IDLIST,
              proposerdetailhouses: [...this.zycqData, ...this.czgfData],
              CityVfyAssignRemark: '',
              ...subsidyData,
            })
            resolve(data)
          } else {
            // reject(new Error('保障用户基本信息未填写完整'))
            this.$message.error({
              text: '保障用户基本信息未填写完整',
            })
          }
        })
      })
    },
    handleReset() {
      this.$confirm({
        title: '确认清空保障用户基本信息数据?',
        content: '清空后需要重新填写',
        okType: 'danger',
        onOk: () => {
          this.form.resetFields()
          this.assureData = []
          this.unAssureData = []
          this.zycqData = []
          this.czgfData = []
          this.$refs.assureTable.refresh(true)
          this.$message.success({
            text: '已清空数据',
          })
        },
      })
    },
    handleHousCategoryChange(e) {
      this.zycqData = []
      this.czgfData = []
    },
    handleAdd(key) {
      this.form.validateFields(['ApplyClass', 'StrDegress', 'HousCategory'], (err, values) => {
        if (!err) {
          this[`${key}Data`] = {}
          this.editIndex = ''
          this[key] = true
        }
      })
    },
    handleEdit(row, index, key) {
      const zeros = this.assureData.filter((item) => item.Relation === 0)
      if (zeros.length == 0) {
        // row.isapplicant = true
        // row.isapplicant = false
        this.applicant = false
        // this.editData.proposerdetail[0].isapplicant = true
      }
      this[`${key}Data`] = row
      this.editIndex = index
      this[key] = true
    },
    handleTableFormChange(e, key) {
      const { type, data, selectApplicant } = e
      this.applicant = selectApplicant
      if (type === 'add') {
        // this[`${key}Data`].push(data)
        if (data.Relation == 0) {
          this[`${key}Data`].unshift(data)
        } else {
          this[`${key}Data`].push(data)
        }
        this.$refs[`${key}Table`].refresh()
      } else {
        if (data.Relation == 0) {
          // this.$set(this[`${key}Data`], 0, data)
          // this.handleDel(data, this.editIndex, key)
          this[`${key}Data`].splice(this.editIndex, 1)
          this[`${key}Data`].unshift(data)
        } else {
          this[`${key}Data`].splice(this.editIndex, 1)
          this[`${key}Data`].push(data)
          // this.$set(this[`${key}Data`], this.editIndex, data)
        }
        // this.$set(this[`${key}Data`], this.editIndex, data)
      }
    },
    handleDel(row, index, key) {
      if (this.IDLIST) {
        this.IDLIST = this.IDLIST + ',' + this[`${key}Data`][index].ID
      } else {
        this.IDLIST = this[`${key}Data`][index].ID
      }
      this[`${key}Data`].splice(index, 1)
      // this[`${key}Data`].splice(index, 1)
      // this.$message.success('删除成功')
      // if (row.Relation === 0 && key === 'assure' && this.assureData.length === 1) {
      //   this.assureData[0].Relation = 0
      //   this.assureData[0].RelationName = '申请人'
      // }
      // this.$refs[`${key}Table`].refresh()
      if (row.Relation === 0 && key === 'assure' && this.assureData.length === 1) {
        // this.assureData[0].Relation = 0
        // this.assureData[0].RelationName = '申请人'
        this.applicant = false
      }
      this.$message.success('删除成功')
      this.$refs[`${key}Table`].refresh()
    },
    computedArea() {
      this.$nextTick(() => {
        let area = BigNumber(0)
        this.zycqData.forEach((e) => {
          area = area.plus(e.PropertyOwnArea)
        })
        const length = this.assureData.length || 0
        this.form.setFieldsValue({
          CityVfyNumber: length,
          StrLiveHousingArea: area.toNumber(),
          CityVfyAreaPer: area.dividedBy(length).toNumber() || 0,
        })
      })
    },
  },
}
</script>
<style lang="less" scoped>
.left {
  /deep/ .ant-input-number {
    width: 100% !important;
  }
  /deep/.ant-form-extra {
    color: #faad14;
  }
}
</style>
